package com.smasher.print.em;


import android.app.Dialog;
import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;


import com.smasher.print.em.databinding.DevicelistBinding;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Vector;

public class UsbDeviceSelector extends DialogFragment {

    private ArrayAdapter<String> mDeviceArrayAdapter;
    private final Vector<UsbDevice> mDeviceList = new Vector<>();

    private OnSelectListener mOnSelectListener;
    private DevicelistBinding mBinding;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DevicelistBinding.inflate(inflater, container, false);
        return mBinding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mBinding.buttonScan.setOnClickListener(v -> reSearch());
        mBinding.buttonBace.setOnClickListener(v -> dismiss());
        mDeviceArrayAdapter = new ArrayAdapter<>(requireContext(), R.layout.list_attributes);
        mBinding.pairedDevices.setAdapter(mDeviceArrayAdapter);
        mBinding.pairedDevices.setOnItemClickListener(mOnItemClickListener);
    }

    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();

        if (dialog != null) {
            Window window = dialog.getWindow();
            if (window != null) {
                window.setLayout(getWidth(), getHeight());
            }
        }
    }

    /**
     * can use{@link ViewGroup.LayoutParams#MATCH_PARENT}
     * or {@link ViewGroup.LayoutParams#WRAP_CONTENT}
     * or exactly number
     */
    protected int getWidth() {
        return ViewGroup.LayoutParams.MATCH_PARENT;
    }

    /**
     * can use{@link ViewGroup.LayoutParams#MATCH_PARENT}
     * or {@link ViewGroup.LayoutParams#WRAP_CONTENT}
     * or exactly number
     */
    protected int getHeight() {
        return ViewGroup.LayoutParams.MATCH_PARENT;
    }

    public void setOnSelectListener(OnSelectListener listener) {
        mOnSelectListener = listener;
    }

    //列出所有USB设备
    private void reSearch() {
        mDeviceList.clear();
        mBinding.buttonScan.setEnabled(false);
        HashMap<String, UsbDevice> devices = getAllUsbDevices();
        Vector<String> devicesArray = new Vector<>();
        Iterator<UsbDevice> deviceIterator = devices.values().iterator();
        if (!devices.isEmpty()) {
            while (deviceIterator.hasNext()) {
                UsbDevice device = deviceIterator.next();
                UsbInterface usbInterface = device.getInterface(0);
                // 不是我们的设备类型，返回
                if (usbInterface.getEndpointCount() == 2) {
                    String name = device.getDeviceName();
                    int vid = device.getVendorId();
                    int pid = device.getProductId();
                    devicesArray.add(name + "  vid: " + vid + "  pid: " + pid);
                    mDeviceList.add(device);
                }
            }
        }
        mDeviceArrayAdapter = new ArrayAdapter<>(requireContext(), R.layout.list_attributes, devicesArray);
        mBinding.pairedDevices.setAdapter(mDeviceArrayAdapter);
        mDeviceArrayAdapter.notifyDataSetChanged();

        mBinding.buttonScan.setEnabled(true);
    }

    public boolean isShowing() {
        return getDialog() != null && getDialog().isShowing();
    }

    // 获得所有的USB设备
    private HashMap<String, UsbDevice> getAllUsbDevices() {
        // 列出所有的 usb 设备
        UsbManager manager = (UsbManager) requireContext().getSystemService(Context.USB_SERVICE);
        return manager.getDeviceList();
    }

    private final AdapterView.OnItemClickListener mOnItemClickListener =
            (parent, view, position, id) -> {
                int len = mDeviceList.size();
                if (position < 0 || position >= len) {
                    return;
                }
                UsbDevice device = mDeviceList.get(position);
                if (mOnSelectListener != null) {
                    mOnSelectListener.onSelect(device);
                }
            };


    public interface OnSelectListener {
        void onSelect(UsbDevice device);
    }

    public static UsbDeviceSelector newInstance() {
        Bundle args = new Bundle();
        UsbDeviceSelector fragment = new UsbDeviceSelector();
        fragment.setArguments(args);
        return fragment;
    }
}
